package gen.tools.deployByDelivery;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ChkIsReloadNeed extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ChkIsReloadNeed() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		String[] depFileStrArray = request.getParameter("depFileString").split( wid.TOKENONE );
		String sql = "SELECT reloadFn FROM reloadlist WHERE fn=?";
		
		boolean isReloadNeed = false;	//預設不用重新上下
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = wid.getConn();
			ps = conn.prepareStatement(sql);
			for(int i=0; i<depFileStrArray.length ; i++ ) {
				ps.setString(1, depFileStrArray[i]);
				rs = ps.executeQuery();
				while( rs.next() ) {	//有設定這個檔案的部署必須重新reload其它檔案
					String reloadFn = rs.getString("reloadFn");	//必須被reload的檔案
					boolean isOccur = false;
					for(int j=0; j<depFileStrArray.length ; j++ ) {
						if( reloadFn.equalsIgnoreCase( depFileStrArray[j] ) ) {	//相同表示已存在於此次部署的檔案清單中，故無需再進行reload
							isOccur = true;
							break;	//出現了，可以跳出這個for loop了
						}
					}
					if( !isOccur ) {	//沒出現，表示必須額外進行重新上下
						isReloadNeed = true;
						break;	//即然確定要執行reload，那 while loop也沒有再跑的必要了 
					}
				}
			}
		} catch ( Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		
		response.getWriter().write( String.valueOf( isReloadNeed ) );
		
	}
}
